import 'package:flutter/material.dart'; 
import 'package:kxy_flutter_app/components/refresh_header.dart';
import 'package:kxy_flutter_app/r.dart';
import 'package:kxy_flutter_app/view/my/action_list_widget.dart';
import 'package:kxy_flutter_app/view/my/head_widget.dart';
import 'package:kxy_flutter_app/view/root/view_model/navigation_model.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'view_model/my_view_model.dart';

class MyView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyViewState();
  }
}

class _MyViewState extends State<MyView> with AutomaticKeepAliveClientMixin {
  RefreshController refreshController = new RefreshController();
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(R.assetsMyBg),
          fit: BoxFit.fitWidth,
          alignment: Alignment.topCenter,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          child: body(),
        ),
      ),
    );
  }

  Widget body() {
    return Consumer<MyViewModel>(
      builder: (cxt, myModel, child) {
        var loadFuture = myModel.isLoad ? Future.value() : myModel.load();
        return FutureBuilder(
          future: loadFuture,
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return create(myModel);
            }
            return Container();
          },
        );
      },
    );
  }

  Widget create(MyViewModel myModel) {
    var view = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        HeadWidget(user: myModel.user),
        ActionListWidget(),
        Expanded(child: Container(color: Colors.white)),
      ],
    );
    return SmartRefresher(
      controller: refreshController,
      enablePullDown: true,
      enablePullUp: false,
      header: RefreshHeader(),
      onRefresh: () async {
        var navModel = Provider.of<NavigationModel>(context, listen: false);
        await navModel.refreshNoticeCount(withNotify: false);
        await myModel.load();
        refreshController.refreshCompleted();
      },
      child: view,
    );
  }

  @override
  bool get wantKeepAlive => true;
}
